package cn.ms.neural.common.log.mdc;

import java.util.Map;

import org.apache.logging.log4j.ThreadContext;

/**
 * The Log4j2 Thread Context(MDC)
 * <br>
 * Including the ThreadContext when writing logs
 * The PatternLayout provides mechanisms to print the contents of the ThreadContext Map and Stack.
 * Use %X by itself to include the full contents of the Map.
 * Use %X{key} to include the specified key.
 * Use %x to include the full contents of the Stack.
 * 
 * @author lry
 */
public class Log4j2MDC<REQ, RES> {

	public static void putMDC(String key, String value) throws Throwable {
		ThreadContext.put(key, value);
	}

	public static void clearAll() {
		ThreadContext.clearAll();
	}

	public RES putMDCs(Map<String, String> data, REQ req, IMDC<REQ, RES> mdc) throws Throwable {
		try {
			if (data != null) {
				if (!data.isEmpty()) {
					for (Map.Entry<String, String> entry : data.entrySet()) {
						ThreadContext.put(entry.getKey(), entry.getValue());
					}
				}
			}
			return mdc.mdc(req);
		} finally {
			ThreadContext.clearAll();
		}
	}

	public RES putMDCs(String[] data, REQ req, IMDC<REQ, RES> mdc) throws Throwable {
		try {
			if (data != null) {
				if (data.length > 0) {
					for (int i = 0; i < data.length;) {
						ThreadContext.put(data[i], data[i + 1]);
						i += 2;
					}
				}
			}
			return mdc.mdc(req);
		} finally {
			ThreadContext.clearAll();
		}
	}
	
	public RES putMDCs(REQ req, IMDC<REQ, RES> mdc,Object... data) throws Throwable {
		try {
			if (data != null) {
				if (data.length > 0) {
					for (int i = 0; i < data.length;) {
						ThreadContext.put(String.valueOf(data[i]), String.valueOf(data[i + 1]));
						i += 2;
					}
				}
			}
			return mdc.mdc(req);
		} finally {
			ThreadContext.clearAll();
		}
	}
	
}
